<template>
  <div>
    <video
      ref="videoElement"
      id="videoElement"
      controls
      style="width: 100%; height: 500px"
    ></video>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import flvjs from "flv.js";
import axios from "axios";
import { get_video, video_detail } from "@/api/index";

const data_list = ref([]);
const url = ref("");
const current = ref("0");
const total_piece = ref(null);
onMounted(() => {
  fetchVideoDetail();
});

const fetchVideoDetail = async () => {
  const params = {
    video_id: 2,
  };
  const { data } = await video_detail(params);
  total_piece.value = data.piece_number;
  startPlayback();
};

const startPlayback = (piece_size) => {
  const videoElement = document.getElementById("videoElement");
  if (flvjs.isSupported()) {
    let player = flvjs.createPlayer({
      type: "flv",
      isLive: false,
    });

    player.attachMediaElement(videoElement); //将播放实例注册到节点
    player.load();
    player.play();

    const loadSegment = async () => {
      try {
        const params = {
          video_id: 2,
          piece_number: current.value,
        };
        const { data } = await axios.get("/video/get_video", {
          responseType: "blob",
          params,
        });
        current.value++;
        try {
          const flvBlob = new Blob([data], { type: "video/x-flv" });
          const flvUrl = URL.createObjectURL(flvBlob);
          console.log("flvUrl", flvUrl);
          player.unload(); // 取消数据流加载
          player.detachMediaElement(); // 将播放实例从节点中取出

          videoElement.addEventListener("loadedmetadata", () => {
            video.duration = 600;
            console.log(`Video duration set to ${video.duration} seconds`);
          });
          player = flvjs.createPlayer({
            type: "flv",
            isLive: false,
            url: flvUrl,
          });
          player.attachMediaElement(videoElement);
          player.load();
          player.play();
        } catch (error) {
          console.error("创建 Blob 或 URL 时发生错误:", error);
        }
      } catch (error) {
        console.error("错误:", error);
      }
    };
    loadSegment();

    videoElement.addEventListener("ended", () => {
      if (current.value < total_piece.value) {
        loadSegment();
      } else {
        console.log("All segments played");
      }
    });
  } else {
    console.error("FLV.js 不支持此浏览器");
  }
};
</script>

<style scoped>
video {
  width: 100%;
  height: auto;
}
</style>
